package com.icat.house.model;

import java.util.List;

import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;

@TableBind(tableName = "house_info")
public class HouseInfo extends BaseModel<HouseInfo> {

	private static final long serialVersionUID = 1L;
	public static final HouseInfo dao = new HouseInfo();

	public List<HouseInfo> findBuildings() {
		return find("select buildings from house_info GROUP BY buildings ORDER BY buildings asc");
	}

	public List<HouseInfo> findHouseByBuildings(int buildings) {
		return find("select * from house_info where buildings=? ORDER BY unit asc", buildings);
	}

	public List<HouseInfo> findByParam(String param, int status) {
		StringBuilder builder = new StringBuilder();
		builder.append("select * from house_info");
		StringBuilder stringBuilder = new StringBuilder();
		if (StrKit.notBlank(param)) {
			String str = " where (buildings  in (" + param + ") or room_no in (" + param + "))";
			stringBuilder.append(str);
		}
		if (status >= 0) {
			if (StrKit.notBlank(stringBuilder.toString())) {
				stringBuilder.append(" and status = " + status);
			} else {
				stringBuilder.append(" where  status = " + status);
			}
		}
		builder.append(stringBuilder);
		builder.append(" order by buildings asc ,unit asc ");
		return find(builder.toString());
	}

	public boolean save(String room_no, int buildings, int unit, double acreage, double price, String adviser) {
		HouseInfo info = new HouseInfo();
		info.set("room_no", room_no);
		info.set("buildings", buildings);
		info.set("unit", unit);
		info.set("acreage", acreage);
		info.set("price", price);
		info.set("total_price", price * acreage);
		info.set("adviser", adviser);
		return info.save();
	}

	public HouseInfo updateStauts(String id) {
		return findFirst("select id,status from house_info where id = ?", id);
	}

	public void updateHouse(int user_id, int status) {
		Db.update(
				"update house_info set `status` = 0 where id in(select room_id from user_trade_room where user_id =? and `status`=?)",
				user_id, status);
		Db.update("delete from user_trade_room where  user_id =? and `status`=?", user_id, status);
	}
}